import axios from 'axios'
import { Channel } from '../types/channel'

export const minus = (
  payload: number
): { type: 'counter/add' | 'counter/minus'; payload: number } => {
  // 这里面返回的是同步的action
  return { type: 'counter/minus', payload }
}

export const add = (
  payload: number
): { type: 'counter/add' | 'counter/minus'; payload: number } => {
  // 这里面返回的是同步的action
  return { type: 'counter/add', payload }
}

// 异步action
export const asyncAdd = (payload: number): any => {
  // 异步里面记得调用同步
  return (dispatch: any) => {
    setTimeout(() => {
      // 一定一定要调用同步
      dispatch(add(payload))
    }, 2000)
  }
}

// { type: 'channel/setChannels'; payload: Channel[] } 是手动的给它添加了返回值约束
export const setChannels = (
  payload: Channel[]
): { type: 'channel/setChannels'; payload: Channel[] } => {
  return {
    type: 'channel/setChannels',
    payload
  }
}

export const asyncGetChannels = (): any => {
  return async (dispatch: any) => {
    const res = await axios.get(
      'http://huangjiangjun.top:3001/api/channel/list'
    )

    console.log('---res---', res)
    dispatch(setChannels(res.data.data))
  }
}
